package com.brk.socket.util;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWTSigner;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.internal.com.fasterxml.jackson.databind.ObjectMapper;
import com.brk.socket.common.ResultCodeEnum;
import com.brk.socket.exception.MyException;

import java.util.HashMap;
import java.util.Map;

/**
 * @author brk
 * @date 2023/7/17 14:19
 * @Description:
 */
public class JwtUtil {

    private static final String SECRET = "XX#$%()(#*!()!KL<><MQLMNQNQJQK sdfkjsdrow32234545fdf>?N<:{LWPW";

    private static final String EXP = "exp";

    private static final String PAYLOAD = "payload";


    /**
     * 加密，传入对象和有效期
     * @param object
     * @param maxAge
     * @return
     */
    public static <T> String sign(T object, long maxAge) {
        try {
            final JWTSigner signer = new JWTSigner(SECRET);
            //转换载荷信息
            final Map<String, Object> claims = new HashMap<String, Object>();
            ObjectMapper mapper = new ObjectMapper();
            String jsonString = mapper.writeValueAsString(object);
            //放入载荷信息
            claims.put(PAYLOAD, jsonString);
            //设置时间
            claims.put(EXP, System.currentTimeMillis() + maxAge);
            return signer.sign(claims);
        } catch(Exception e) {
            return null;
        }
    }


    /**
     * 解密，传入一个加密后的token字符串和解密后的类型
     * @param jwt
     * @param classT
     * @return
     */
    public static<T> T unsign(String jwt, Class<T> classT) {
        final JWTVerifier verifier = new JWTVerifier(SECRET);
        try {
            final Map<String,Object> claims= verifier.verify(jwt);
            if (claims.containsKey(EXP) && claims.containsKey(PAYLOAD)) {
                long exp = (Long)claims.get(EXP);
                long currentTimeMillis = System.currentTimeMillis();
                if (exp > currentTimeMillis) {
                    String json = (String)claims.get(PAYLOAD);

                    return JSON.toJavaObject(JSON.parseObject(json), classT);
                }
                throw new MyException(ResultCodeEnum.TOKEN_EXPIRE);
            }
            throw new MyException(ResultCodeEnum.TOKEN_ILLEGAL);
        } catch (Exception e) {
            throw new MyException(ResultCodeEnum.UNKNOWN_ERROR);
        }
    }

}
